package cn.aitrox.ry.service.image.dao.impl;

import cn.aitrox.ry.service.image.dao.ImageDao;
import cn.aitrox.ry.service.image.entity.ImageMongoEntity;
import cn.aitrox.ry.service.image.repository.ImageRepository;
import cn.aitrox.ry.util.ArrayUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class ImageDaoImpl implements ImageDao {

    @Autowired
    private ImageRepository repository;

    @Autowired
    private MongoTemplate mongoTemplate;

    public List<ImageMongoEntity> query(List<String> groups, String groupType, List<String> modes, List<Integer> numbers) {
        if (ArrayUtil.isEmpty(groups) || StringUtils.isEmpty(groupType)) {
            return new ArrayList<>();
        }

        Query query = new Query();
        query.addCriteria(Criteria.where(ImageMongoEntity.FIELD_GROUP).in(groups));
        query.addCriteria(Criteria.where(ImageMongoEntity.FIELD_GROUP_TYPE).is(groupType));
        if (!ArrayUtil.isEmpty(modes)) {
            query.addCriteria(Criteria.where(ImageMongoEntity.FIELD_MODE).in(modes));
        }
        if (!ArrayUtil.isEmpty(numbers)) {
            query.addCriteria(Criteria.where(ImageMongoEntity.FIELD_NUMBER).in(numbers));
        }
        return mongoTemplate.find(query, ImageMongoEntity.class);

    }

    @Override
    public void batchSave(List<ImageMongoEntity> list) {
        repository.saveAll(list);
    }

    @Override
    public void deleteByGroupGroupTypeMode(String group, String groupType, String mode) {
        Query query = new Query();
        query.addCriteria(Criteria.where(ImageMongoEntity.FIELD_GROUP).is(group));
        query.addCriteria(Criteria.where(ImageMongoEntity.FIELD_GROUP_TYPE).is(groupType));
        query.addCriteria(Criteria.where(ImageMongoEntity.FIELD_MODE).is(mode));
        mongoTemplate.remove(query, ImageMongoEntity.class);
    }

}
